//
//  LEPlayVC.m
//  qqqqqq
//
//  Created by iOSer on 2017/3/15.
//  Copyright © 2017年 iOSer. All rights reserved.
//

#import "LEPlayVC.h"
#import "LEMyHeaderView.h"
#import "LENowHeaderView.h"
#import "LENowTableCell.h"
#import "LEMyTableCell.h"
#import "LEReSiteView.h"
#import "LESettingView.h"
#import "LEAlipayView.h"
#import "LEBuyVerifyView.h"
#import "LEHintView.h"
#import "LEDefaultHintView.h"
#import "LECommodity.h"
#import "LEOwnCommodityModel.h"
#import "LEMarketHandle.h"
#import "LEUserInfoModel.h"
#import "LEUserInfoCoreDataManager.h"
typedef NS_ENUM(NSInteger,openItem) {
    nilOpen = 0,
    openSite,
    openAlipay,
    openHospital,
    openIntermdiary,
    openSetting,
    openBuyVerify,
    openSaleVerify,
    openHint,
    openBehaviorHint,
    openReLoadHint
};


static NSString *moneyKey = @"moneyNum";
static NSString *aliPayKey = @"aliPayNum";
static NSString *healthKey = @"healthNum";
static NSString *reputationKey = @"reputationNum";
static NSString *weekKey = @"weekNum";

@interface LEPlayVC ()<UITableViewDelegate,UITableViewDataSource,LEReSiteViewDelegate,LESettingViewDelegate,LEBuyVerifyViewDelegate,LEAlipayViewDelegate,LEDefaultHintViewDelegate>
@property(nonatomic,strong) UIButton *settingBtn;
@property(nonatomic,strong) UILabel *moneyLab;
@property(nonatomic,strong) UILabel *weekLab;
@property(nonatomic,strong) UILabel *healthLab;
@property(nonatomic,strong) UILabel *reputationLab;
@property(nonatomic,strong) UILabel *depositLab;
@property(nonatomic,strong) UITableView *nowTable;
@property(nonatomic,strong) UITableView *myTable;
@property(nonatomic,strong) UIButton *reSiteBtn;
@property(nonatomic,strong) UIButton *aliPayBtn;
@property(nonatomic,strong) UIButton *hospitalBtn;
@property(nonatomic,strong) UIButton *intermediaryBtn;
@property(nonatomic,copy) NSArray *CommodityArray;
@property(nonatomic,strong) NSMutableArray *nowDataSourceArrayM;
@property(nonatomic,strong) NSMutableArray *myDataSourceArrayM;
@property(nonatomic,strong) LEUserInfoModel *userInfo;
@property(nonatomic,strong) LEReSiteView *reSiteView;
@property(nonatomic,strong) LESettingView *settingView;
@property(nonatomic,strong) LEAlipayView *alipayView;
@property(nonatomic,strong) LEBuyVerifyView *buyVerifyView;
@property(nonatomic,strong) LEBuyVerifyView *saleVerifyView;
@property(nonatomic,strong) LEHintView *hintView;
@property(nonatomic,strong) LEHintView *behaviorHintView;
@property(nonatomic,strong) LEDefaultHintView *reLoadHintView;
@property(nonatomic,strong) LEDefaultHintView *gameOverView;
@property(nonatomic,assign) openItem isOpenItem;
@property(nonatomic,strong) NSIndexPath *nowSelectedCellIndex;
@property(nonatomic,strong) NSIndexPath *buySelectedCellIndex;
@property(nonatomic,assign) BOOL isRefreshNowTable;
@end

@implementation LEPlayVC
/*
 逻辑：
 @@@ - 处理概率 id 概率
 $$$  - 对应一段逻辑判断触发事件与否 如果是哪个物品涨价
 *** - 对应一段逻辑判断触发事件与否 是否挨打 是否被偷  是否名气被搞臭
 
 商品：-对应一个文字   对应一个正常价格范围  低价范围   高价范围   一段涨价文字  一段降价文字
Q7汽车
乱想电脑
爱疯
24K氪金
扩容U盘
大米手环
醇香地沟油
前男友面膜
黑心棉口罩
AV光盘
 */
- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view setBackgroundColor:HEXColor(0xffffff, 1)];
    self.isOpenItem = nilOpen;
    self.isRefreshNowTable = YES;
    [self setupCommoditys];
    if (self.loadingUserInfo) {
        [self setupProgress];
    }else{
        [self setupNowDataSource];
        [self setupData];
    }
    [self setupKVO];
    
}

-(void)setupCommoditys{
    LECommodity *CarComm = [[LECommodity alloc] initWithName:@"Q20汽车" lowText:@"据传：因为污染，将推出更加严厉的限行政策。买车除了车震，基本毫无用途。车市顾客寥寥无几。" highliText:@"据传：车贩利用政策漏洞，二手汽车车牌可过户。二手车市场立即沸腾，用户争相购买。" defaultPrice:@[@80000,@120000] lowPrice:@[@20000,@40000] highliPrice:@[@180000,@250000] Probability:0.1];
    LECommodity *ComputerComm = [[LECommodity alloc] initWithName:@"橘子电脑" lowText:@"据传：橘子电脑偷偷使用三流工厂代工，硬件品质恶劣被曝光。用户失去购买兴趣。" highliText:@"据传：橘子电脑加大广告力度，品牌影响力上升。群众纷纷购买，各种机型价格上涨。" defaultPrice:@[@10000,@15000] lowPrice:@[@5000,@8000] highliPrice:@[@20000,@25000] Probability:0.1];
    
    LECommodity *PhoneComm = [[LECommodity alloc] initWithName:@"爱疯7P" lowText:@"据传：爱疯手机电池爆炸，吓坏用户。手机销量一路下滑，商家降价促销。" highliText:@"据传：爱疯手机饥饿营销，有钱买不到。粉丝连夜排队购买。黄牛趁机抬高手机价格。" defaultPrice:@[@5000,@8000] lowPrice:@[@2000,@3000] highliPrice:@[@10000,@15000] Probability:0.1];
    LECommodity *GoldComm = [[LECommodity alloc] initWithName:@"24K氪金" lowText:@"据传：国际金融大鳄操控期货市场，氪金狗眼不再流行。氪金清仓甩卖。" highliText:@"据传：中国大妈听说氪金狗眼是个好东西，纷纷囤货，氪金价格一路上涨。" defaultPrice:@[@2000,@3000] lowPrice:@[@800,@1000] highliPrice:@[@4000,@5000] Probability:0.1];
    LECommodity *UPanComm = [[LECommodity alloc] initWithName:@"扩容U盘" lowText:@"据传：部分互联网网盘未受清查影响，依然坚挺，吸引众多用户。扩容U盘销量下跌。" highliText:@"据传：互联网网盘因涉黄被严查，多家网盘倒闭。扩容U盘出货量暴增，价格猛涨。" defaultPrice:@[@800,@1000] lowPrice:@[@300,@500] highliPrice:@[@1500,@2000] Probability:0.1];
    LECommodity *ShouHuanComm = [[LECommodity alloc] initWithName:@"大米手环" lowText:@"据传：很多青年人发现，每天出去走一走，还是不如在家看片撸啊撸来的舒服。运动手环销量下滑。" highliText:@"据传：生命在于运动，每天行走一万步，有益身体健康。大米手环成为必备。" defaultPrice:@[@400,@550] lowPrice:@[@100,@200] highliPrice:@[@600,@800] Probability:0.1];
    LECommodity *OilComm = [[LECommodity alloc] initWithName:@"浓香地沟油" lowText:@"据传：专家称地沟油吃了会阳痿，大部分人都不敢再食用地沟油。地沟油价格萎靡。" highliText:@"据传：市场上大肆宣传虚假广告，宣称地沟油就是香，每天都吃身体棒。地沟油成为紧俏商品。" defaultPrice:@[@200,@300] lowPrice:@[@80,@100] highliPrice:@[@500,@550] Probability:0.1];
    LECommodity *MaskComm = [[LECommodity alloc] initWithName:@"前男友面膜" lowText:@"据传：美容养颜不如用黄瓜，用黄瓜不如找男朋友。前男友面膜价格一路下滑。" highliText:@"据传：美容养颜还是用前男友面膜最有效，喷在脸上，立即见效。" defaultPrice:@[@100,@150] lowPrice:@[@50,@60] highliPrice:@[@300,@350] Probability:0.1];
    LECommodity *KouZhaoComm = [[LECommodity alloc] initWithName:@"爽歪歪口罩" lowText:@"据传：西北风强力吹散雾霾，口罩严重积压，低价抛售。" highliText:@"据传：帝都雾霾橙色预警，市民疯狂抢购口罩。爽歪歪口罩一时引领时尚，供不应求。" defaultPrice:@[@30,@50] lowPrice:@[@10,@15] highliPrice:@[@90,@150] Probability:0.1];
    LECommodity *AVComm = [[LECommodity alloc] initWithName:@"AV光盘" lowText:@"据传：一些盗版AV光盘里面暗藏黄色小片，受到监管部门大力打击，几乎无人问津。" highliText:@"据传：经常看AV光盘，能提高编码能力。程序员疯狂抢购，AV光盘价格大涨。" defaultPrice:@[@9,@14] lowPrice:@[@2,@6] highliPrice:@[@30,@48] Probability:0.2];
    
    self.CommodityArray = @[CarComm ,ComputerComm,PhoneComm,GoldComm,UPanComm,ShouHuanComm,OilComm,MaskComm,KouZhaoComm,AVComm];
    for (LECommodity *idCom in self.CommodityArray) {
        idCom.isRefresh = YES;
        idCom.priceType = defaultPrice;
    }
    
    
}

-(void)setupNowDataSource{
    self.nowDataSourceArrayM = [NSMutableArray arrayWithArray:self.CommodityArray];
    for (int i = 0; i<5; ++i) {
        int arcNum = arc4random()%(self.nowDataSourceArrayM.count-1);
        [self.nowDataSourceArrayM removeObjectAtIndex:arcNum];
    }
}

-(void)setupProgress{
    self.nowDataSourceArrayM = [NSMutableArray arrayWithArray:self.loadingUserInfo.userComModelArray];
    self.myDataSourceArrayM = [NSMutableArray arrayWithArray:self.loadingUserInfo.ownComModelArray];
    self.userInfo = self.loadingUserInfo;
}
-(void)setupData{
    [self.userInfo setValue:@"100" forKey:moneyKey];
    [self.userInfo setValue:@"0" forKey:aliPayKey];
    [self.userInfo setValue:@"100" forKey:healthKey];
    [self.userInfo setValue:@"100" forKey:reputationKey];
    [self.userInfo setValue:@"50" forKey:weekKey];
}
-(void)setupKVO{
    
    [self.userInfo addObserver:self forKeyPath:moneyKey options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:NULL];
    [self.userInfo addObserver:self forKeyPath:aliPayKey options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:NULL];
    [self.userInfo addObserver:self forKeyPath:healthKey options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:NULL];
    [self.userInfo addObserver:self forKeyPath:reputationKey options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:NULL];
    [self.userInfo addObserver:self forKeyPath:weekKey options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:NULL];
    self.moneyLab.text = [NSString stringWithFormat:@"现金:￥%@",[self.userInfo valueForKey:moneyKey]];
    self.healthLab.text = [NSString stringWithFormat:@"健康:￥%@",[self.userInfo valueForKey:healthKey]];
    self.reputationLab.text = [NSString stringWithFormat:@"名声:￥%@",[self.userInfo valueForKey:reputationKey]];
    self.depositLab.text = [NSString stringWithFormat:@"存款:￥%@",[self.userInfo valueForKey:aliPayKey]];
    self.weekLab.text = [NSString stringWithFormat:@"周:%@",[self.userInfo valueForKey:weekKey]];
}

-(void)viewWillAppear:(BOOL)animated{
    [self.navigationController setNavigationBarHidden:YES animated:NO];
    [self setupUI];
}

-(void)dealloc{
    
    [self.userInfo removeObserver:self forKeyPath:moneyKey];
    [self.userInfo removeObserver:self forKeyPath:aliPayKey];
    [self.userInfo removeObserver:self forKeyPath:healthKey];
    [self.userInfo removeObserver:self forKeyPath:reputationKey];
    [self.userInfo removeObserver:self forKeyPath:weekKey];
}
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    if([keyPath isEqualToString:moneyKey])
    {
        self.moneyLab.text = [NSString stringWithFormat:@"现金:￥%@",[self.userInfo valueForKey:moneyKey]];
    }else if([keyPath isEqualToString:healthKey]){
        self.healthLab.text = [NSString stringWithFormat:@"健康:￥%@",[self.userInfo valueForKey:healthKey]];
    }else if([keyPath isEqualToString:reputationKey]){
        self.reputationLab.text = [NSString stringWithFormat:@"名声:￥%@",[self.userInfo valueForKey:reputationKey]];
    }
    else if([keyPath isEqualToString:aliPayKey]){
        self.depositLab.text = [NSString stringWithFormat:@"存款:￥%@",[self.userInfo valueForKey:aliPayKey]];
    }else if([keyPath isEqualToString:weekKey]){
        self.weekLab.text = [NSString stringWithFormat:@"周:%@",[self.userInfo valueForKey:weekKey]];
    }
}
-(void)setupUI{
    
    
    [self.view addSubview:self.moneyLab];
    [self.view addSubview:self.healthLab];
    [self.view addSubview:self.reputationLab];
    [self.view addSubview:self.depositLab];
    [self.view addSubview:self.weekLab];
    [self.view addSubview:self.nowTable];
    [self.view addSubview:self.myTable];
    [self.view addSubview:self.buyVerifyView];
    [self.view addSubview:self.saleVerifyView];
    
    
    [self.view addSubview:self.reSiteView];
    [self.view addSubview:self.reSiteBtn];
    [self.view addSubview:self.alipayView];
    [self.view addSubview:self.aliPayBtn];
    [self.view addSubview:self.hospitalBtn];
    [self.view addSubview:self.intermediaryBtn];
    [self.view addSubview:self.settingView];
    [self.view addSubview:self.settingBtn];
    [self.view addSubview:self.gameOverView];
    [self.view addSubview:self.reLoadHintView];
    [self.view addSubview:self.behaviorHintView];
    [self.view addSubview:self.hintView];
    [_settingBtn makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(GGRealValue(5));
        make.right.equalTo(self.view).offset(-GGRealValue(5));
        make.size.equalTo(CGSizeMake(GGRealValue(18), GGRealValue(18)));
    }];
    [_moneyLab makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(GGRealValue(5));
        make.left.equalTo(self.view).offset(GGRealValue(10));
        make.height.equalTo(@(GGRealValue(12)));
    }];
    [_healthLab makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(GGRealValue(5));
        make.left.equalTo(_moneyLab.mas_right).offset(GGRealValue(5));
        make.height.equalTo(@(GGRealValue(12)));
    }];
    [_reputationLab makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(GGRealValue(5));
        make.left.equalTo(_healthLab.mas_right).offset(GGRealValue(5));
        make.height.equalTo(@(GGRealValue(12)));
    }];
    [_depositLab makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(GGRealValue(5));
        make.left.equalTo(_reputationLab.mas_right).offset(GGRealValue(5));
        make.height.equalTo(@(GGRealValue(12)));
    }];
    [_weekLab makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(GGRealValue(5));
        make.right.equalTo(_settingBtn.mas_left).offset(-GGRealValue(10));
        make.height.equalTo(@(GGRealValue(12)));
    }];
    [_nowTable makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_moneyLab.mas_bottom).offset(GGRealValue(10));
        make.left.equalTo(self.view).offset(GGRealValue(20));
        make.width.equalTo(SCREEN_WIDTH/2-GGRealValue(40));
        make.bottom.equalTo(self.view).offset(-GGRealValue(30));
    }];
    [_myTable makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_moneyLab.mas_bottom).offset(GGRealValue(10));
        make.right.equalTo(self.view).offset(-GGRealValue(20));
        make.width.equalTo(SCREEN_WIDTH/2-40);
        make.bottom.equalTo(self.view).offset(-GGRealValue(30));
    }];
    [_reSiteBtn makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.view).offset(-GGRealValue(5));
        make.left.equalTo(self.view).offset(20);
        make.size.equalTo(CGSizeMake((SCREEN_WIDTH-100)/4, GGRealValue(20)));
    }];
    [_aliPayBtn makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.view).offset(-GGRealValue(5));
        make.left.equalTo(_reSiteBtn.mas_right).offset(20);
        make.size.equalTo(CGSizeMake((SCREEN_WIDTH-100)/4, GGRealValue(20)));
    }];
    [_hospitalBtn makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.view).offset(-GGRealValue(5));
        make.left.equalTo(_aliPayBtn.mas_right).offset(20);
        make.size.equalTo(CGSizeMake((SCREEN_WIDTH-100)/4, GGRealValue(20)));
    }];
    [_intermediaryBtn makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.view).offset(-GGRealValue(5));
        make.left.equalTo(_hospitalBtn.mas_right).offset(20);
        make.size.equalTo(CGSizeMake((SCREEN_WIDTH-100)/4, GGRealValue(20)));
    }];
    
}
#pragma mark - tableView
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (tableView == self.nowTable) {
        return 5;
    }else{
        return self.myDataSourceArrayM.count;
    }
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    id tableCell;
    
    if (tableView == self.nowTable) {
        LECommodity *commodity = self.nowDataSourceArrayM[indexPath.row];
        LENowTableCell *cell = [LENowTableCell LENowTableCellWithTableView:tableView];
        cell.commodity = commodity;
        tableCell = cell;
    }else{
        LEMyTableCell *cell = [LEMyTableCell LEMyTableCellWithTableView:tableView];
        cell.model = self.myDataSourceArrayM[indexPath.row];
        tableCell = cell;
    }
        //完全取消cell的选中状态
    //    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    //修改cell选中颜色
    UITableViewCell *cell = (UITableViewCell *)tableCell;
    cell.selectedBackgroundView = [[UIView alloc] initWithFrame:cell.frame];
    cell.selectedBackgroundView.backgroundColor = HEXColor(0xf5f5f5, 1);
    return cell;
}


//cell的点击事件
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView == self.nowTable) {
        LENowTableCell *cell = (LENowTableCell *)[self.nowTable cellForRowAtIndexPath:indexPath];
        self.nowSelectedCellIndex = indexPath;
        self.isOpenItem = openBuyVerify;
        long buyCount = (self.userInfo.moneyNum/cell.commodity.nowPrice)>=1?self.userInfo.moneyNum/cell.commodity.nowPrice:0;
        [self.buyVerifyView showLEBuyVerifyViewWithType:1 Name:cell.commodity.name andCount:(int)buyCount];
    }else{
        LEMyTableCell *cell = (LEMyTableCell *)[self.myTable cellForRowAtIndexPath:indexPath];
        self.buySelectedCellIndex = indexPath;
        self.isOpenItem = openSaleVerify;
        [self.saleVerifyView showLEBuyVerifyViewWithType:2 Name:cell.model.name andCount:cell.model.count];
    }
    //取消cell选中状态,按下变灰
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if (tableView == self.nowTable) {
        LENowHeaderView *header = [LENowHeaderView LENowHeaderView:tableView];
        return header;
    }else{
        LEMyHeaderView *header = [LEMyHeaderView LEMyHeaderView:tableView];
        return header;
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return GGRealValue(15);
}

#pragma mark - delegate
-(void)leDefaultHintViewOkBtnClickWithHintView:(LEDefaultHintView *)hintView{
    if (hintView == self.reLoadHintView) {
        [self setupCommoditys];
        [self.myDataSourceArrayM removeAllObjects];
        self.userInfo.weekNum = 50;
        self.userInfo.moneyNum = 100;
        self.userInfo.healthNum = 100;
        self.userInfo.reputationNum = 100;
        self.userInfo.aliPayNum = 0;
        [self.myTable reloadData];
        [self.nowTable reloadData];
    }else if (hintView == self.gameOverView){
        [self.navigationController popViewControllerAnimated:YES];
    }
    
}
-(void)alipeyViewClickWithType:(int)type money:(NSString *)money{
    
    if (type == 0) {
        if ([money intValue]!=0 && ![money isEqualToString:@""]) {
            if ([money intValue]<=self.userInfo.moneyNum) {
                [self.userInfo setValue:[NSString stringWithFormat:@"%ld",self.userInfo.aliPayNum + [money intValue]] forKey:aliPayKey];
                [self.userInfo setValue:[NSString stringWithFormat:@"%ld",self.userInfo.moneyNum - [money intValue]] forKey:moneyKey];
            }else{
                [[GGShowHUDTool sharedInstance] showNoHudWith:@"没钱你存鸡毛！"];
            }
        }else{
            [[GGShowHUDTool sharedInstance] showNoHudWith:@"不存你玩我呢？"];
        }
        
    }else{
        if ([money intValue]!=0 && ![money isEqualToString:@""]) {
            if ([money intValue]<=self.userInfo.aliPayNum) {
                [[GGShowHUDTool sharedInstance] showInfoHudWith:@"余额宝扣除10%的手续费"];
                [self.userInfo setValue:[NSString stringWithFormat:@"%ld",self.userInfo.moneyNum + (int)([money intValue] - [money intValue]*0.1)] forKey:moneyKey];
                [self.userInfo setValue:[NSString stringWithFormat:@"%ld",self.userInfo.aliPayNum - [money intValue]] forKey:aliPayKey];
            }else{
                [[GGShowHUDTool sharedInstance] showNoHudWith:@"没钱你取鸡毛！"];
            }
        }else{
            [[GGShowHUDTool sharedInstance] showNoHudWith:@"不取你玩我呢？"];
        }
    }
}
-(void)reSiteClickBtnWithIndex:(NSInteger)index{
    if (self.userInfo.weekNum != 0) {
        [self.userInfo setValue:[NSString stringWithFormat:@"%d",(int)self.userInfo.weekNum-1] forKey:weekKey];
    }
    
    if (self.userInfo.weekNum == 0) {
        
        
        [self.gameOverView showLEDefaultHintViewWithTitle:@"游戏结束" Text:@"别玩了，游戏结束了点击确认返回上一级"];
    }else{
        
        self.nowDataSourceArrayM = [NSMutableArray arrayWithArray:self.CommodityArray];
        for (int i = 0; i<5; ++i) {
            BOOL isRemove = NO;
            NSString *deleteStr = [[LEMarketHandle alloc] calculateCommodityShowProbability];
            for (LECommodity *com in self.nowDataSourceArrayM) {
                if ([com.name isEqualToString:deleteStr]) {
                    [self.nowDataSourceArrayM removeObject:com];
                    isRemove = YES;
                    break;
                }
            }
            if (isRemove == NO) {
                i-=1;
            }
        }
        for (LECommodity *idCom in self.CommodityArray) {
            idCom.isRefresh = YES;
            idCom.priceType = defaultPrice;
        }
        
        if (self.userInfo.aliPayNum>0) {
            [self.userInfo setValue:[NSString stringWithFormat:@"%ld",self.userInfo.aliPayNum + 10] forKey:aliPayKey];
        }
        
        //    NSLog(@"%@",self.nowDataSourceArrayM);
        
        NSString *isBehavior = [[LEMarketHandle alloc] calculateBehaviorProbability];
        if (![isBehavior isEqualToString:@""]) {
            self.isOpenItem = openBehaviorHint;
            if ([isBehavior isEqualToString:@"小偷"]) {
                [self.behaviorHintView showLEBuyVerifyViewWithType:2 Text:@"地铁能把人挤怀孕！小偷偷了你10%现金！"];
                [self.userInfo setValue:[NSString stringWithFormat:@"%ld",self.userInfo.moneyNum - (int)(self.userInfo.moneyNum*0.1)] forKey:moneyKey];
                
            }else{
                [self.behaviorHintView showLEBuyVerifyViewWithType:2 Text:@"听说你卖的盗版AV？你耿哥派人揍了你一顿。"];
                [self.userInfo setValue:[NSString stringWithFormat:@"%ld",self.userInfo.healthNum - 2] forKey:healthKey];
                [self.userInfo setValue:[NSString stringWithFormat:@"%ld",self.userInfo.reputationNum - 2] forKey:reputationKey];
            }
            
        }
        
        
        NSString *str = [[LEMarketHandle alloc] calculateTriggerProbability:self.nowDataSourceArrayM];
        if (![str isEqualToString:@""]) {
            NSString *isHandle = [[LEMarketHandle alloc] calculateLowORHighlightProbability];
            
            for (LECommodity *com in self.nowDataSourceArrayM) {
                if ([com.name isEqualToString:str]) {
                    if ([isHandle isEqualToString:@"Low"]) {
                        com.priceType = lowPrice;
                        [self.hintView showLEBuyVerifyViewWithType:1 Text:com.lowText];
                        //                    NSLog(@"%@降价了",str);
                    }else{
                        com.priceType = HiPrice;
                        [self.hintView showLEBuyVerifyViewWithType:1 Text:com.highliText];
                        //                    NSLog(@"%@涨价了",str);
                    }
                    self.isOpenItem = openHint;
                    break;
                }
            }
        }
        
        //    NSLog(@"%@",str);
        [self.nowTable reloadData];
    }
}


-(void)LESetttingBtnClickWithIndex:(NSInteger)index{
    switch (index) {
        case 0:
            [self.settingView dismissView];
            self.isOpenItem = openReLoadHint;
            [self.reLoadHintView showLEDefaultHintViewWithTitle:@"重新开始" Text:@"你确定重新开始？"];
            break;
        case 1:
            self.userInfo.userComModelArray = self.nowDataSourceArrayM;
            self.userInfo.ownComModelArray = self.myDataSourceArrayM;
            [[LEUserInfoCoreDataManager shareInstance] saveContext:self.userInfo];
            [[GGShowHUDTool sharedInstance] showYesHudWith:@"进度保存成功"];
            break;
        case 2:
            
            [self.navigationController popViewControllerAnimated:YES];
            break;
        default:
            break;
    }
}

-(void)LEBuyVerifyViewBtnClickWithView:(LEBuyVerifyView *)verifyView Text:(NSString *)string{
    
    
    if (verifyView == self.buyVerifyView) {
        if (![string isEqualToString:@"0"] && ![string isEqualToString:@""]) {
            LENowTableCell *cell = (LENowTableCell *)[self.nowTable cellForRowAtIndexPath:self.nowSelectedCellIndex];
            long buyCount = (self.userInfo.moneyNum/cell.commodity.nowPrice)>=1?self.userInfo.moneyNum/cell.commodity.nowPrice:0;
            if ([string intValue]<=buyCount) {
                
                LEOwnCommodityModel *model = [[LEOwnCommodityModel alloc] init];
                model.name = cell.commodity.name;
                model.costing = cell.commodity.nowPrice;
                model.count = [string intValue];
                [self.userInfo setValue:[NSString stringWithFormat:@"%ld",self.userInfo.moneyNum - (cell.commodity.nowPrice*[string intValue])] forKey:moneyKey];
                BOOL isExist = NO;
                for (int i = 0; i<self.myDataSourceArrayM.count; ++i) {
                    LEOwnCommodityModel *nowModel = self.myDataSourceArrayM[i];
                    if ([nowModel.name isEqualToString:cell.commodity.name]) {
                        model.count = [string intValue] + nowModel.count;
                        [self.myDataSourceArrayM replaceObjectAtIndex:i withObject:model];
                        isExist = YES;
                        break;
                    }
                }
                if (isExist == NO) {
                    [self.myDataSourceArrayM addObject:model];
                }
                [self.myTable reloadData];
            }else{
                [[GGShowHUDTool sharedInstance] showNoHudWith:@"买不起就滚！别浪费时间"];
            }
            
        }else{
            [[GGShowHUDTool sharedInstance] showNoHudWith:@"穷逼也敢买东西？滚！！！"];
        }
    }else{
        LEMyTableCell *cell = (LEMyTableCell *)[self.myTable cellForRowAtIndexPath:self.buySelectedCellIndex];
        if (![string isEqualToString:@"0"] && ![string isEqualToString:@""]) {
            if (cell.model.count < [string intValue]) {
                [[GGShowHUDTool sharedInstance] showNoHudWith:@"存货不够你卖毛线？"];
            }else{
                BOOL isHave = NO;
                for (int i = 0; i<5; ++i) {
                    LENowTableCell *nowCell = (LENowTableCell *)[self.nowTable cellForRowAtIndexPath:[NSIndexPath indexPathForRow:i inSection:0]];
                    if ([nowCell.commodity.name isEqualToString:cell.model.name]) {
                        isHave = YES;
                        self.userInfo.moneyNum += nowCell.commodity.nowPrice * [string intValue];
                        for (int i = 0; i<self.myDataSourceArrayM.count; ++i) {
                            LEOwnCommodityModel *saleModel = self.myDataSourceArrayM[i];
                            
                            if ([saleModel.name isEqualToString:cell.model.name]) {
                                if (saleModel.count != [string intValue]) {
                                    saleModel.count = saleModel.count - [string intValue];
                                    [self.myDataSourceArrayM replaceObjectAtIndex:i withObject:saleModel];
                                    [self.myTable reloadData];
                                }else{
                                    [self.myDataSourceArrayM removeObject:saleModel];
                                    [self.myTable reloadData];
                                }
                                break;
                            }
                        }
                        
                        break;
                    }
                }
                if (isHave == NO) {
                    [[GGShowHUDTool sharedInstance] showNoHudWith:@"瞎啊！市场上没有你卖的东西"];
                }
            }
            
        }else{
            [[GGShowHUDTool sharedInstance] showNoHudWith:@"不卖你瞎点个鸡毛！"];
        }
    }
}

#pragma mark - 点击事件
-(void)reSiteBtnClick:(UIButton *)btn{
    btn.selected = !btn.selected;
    if (btn.selected == YES) {
        [self closeOtherItem];
        [self.reSiteView showLERESiteView];
        self.isOpenItem = openSite;
    }else{
        [self.reSiteView dismissView];
    }
    
}
-(void)aliPayBtnClick:(UIButton *)btn{
    btn.selected = !btn.selected;
    if (btn.selected == YES) {
        [self closeOtherItem];
        [self.alipayView showLEAlipayViewWithMoney:self.userInfo.moneyNum andAliMoney:self.userInfo.aliPayNum];
        self.isOpenItem = openAlipay;
    }else{
        [self.alipayView dismissView];
    }
}
-(void)settingBtnClick:(UIButton *)btn{
    btn.selected = !btn.selected;
    if (btn.selected == YES) {
        [self closeOtherItem];
        [self.settingView showLESettingView];
        self.isOpenItem = openSetting;
    }else{
        [self.settingView dismissView];
    }
    
}

-(void)hospitalBtnClick:(UIButton *)btn{
    [self closeOtherItem];
    [[GGShowHUDTool sharedInstance] showInfoHudWith:@"医院暂时不开门"];
}
-(void)intermediaryBtnClick:(UIButton *)btn{
    
    
    [self closeOtherItem];
    [[GGShowHUDTool sharedInstance] showInfoHudWith:@"中介暂时不营业"];
}
-(void)closeOtherItem{
    if (self.isOpenItem != nilOpen) {
        switch (self.isOpenItem) {
            case openSite:
                self.reSiteBtn.selected = NO;
                [self.reSiteView dismissView];
                break;
            case openAlipay:
                self.aliPayBtn.selected = NO;
                [self.alipayView dismissView];
                break;
            case openHospital:
                
                break;
            case openIntermdiary:
                
                break;
            case openSetting:
                self.settingBtn.selected = NO;
                [self.settingView dismissView];
                break;
            case openBuyVerify:
                [self.buyVerifyView dismissView];
                break;
            case openSaleVerify:
                [self.saleVerifyView dismissView];
                break;
            case openHint:
                [self.hintView dismissView];
                break;
            case openBehaviorHint:
                [self.behaviorHintView dismissView];
                break;
            case openReLoadHint:
                [self.reLoadHintView dismissView];
                break;
            default:
                break;
        }
    }
}
//懒加载
-(UITableView *)nowTable{
    if (!_nowTable) {
        
        
        //        [_tableView setContentOffset:CGPointMake(0,200) animated:NO];
        _nowTable = [[UITableView alloc] init];
        //设置数据源
        _nowTable.delegate = self;
        _nowTable.dataSource = self;
        //取消下划线
        _nowTable.separatorStyle = UITableViewCellSelectionStyleNone;
        //隐藏滚动条
        _nowTable.showsVerticalScrollIndicator = NO;
        [_nowTable setTableFooterView:[[UIView alloc] initWithFrame:CGRectZero]];
        _nowTable.layer.borderColor = HEXColor(0x000000, 1).CGColor;
        _nowTable.layer.borderWidth = 0.5;
    }
    
    return _nowTable;
}
-(UITableView *)myTable{
    if (!_myTable) {
        
        
        //        [_tableView setContentOffset:CGPointMake(0,200) animated:NO];
        _myTable = [[UITableView alloc] init];
        //设置数据源
        _myTable.delegate = self;
        _myTable.dataSource = self;
        //取消下划线
        _myTable.separatorStyle = UITableViewCellSelectionStyleNone;
        //隐藏滚动条
        _myTable.showsVerticalScrollIndicator = NO;
        [_myTable setTableFooterView:[[UIView alloc] initWithFrame:CGRectZero]];
        _myTable.layer.borderColor = HEXColor(0x000000, 1).CGColor;
        _myTable.layer.borderWidth = 0.5;
    }
    
    return _myTable;
}
-(UILabel *)moneyLab{
    if (!_moneyLab) {
        _moneyLab = [[UILabel alloc] initWithTitle:@"现金:￥0" color:HEXColor(0x000000, 1) sizeFont:GGRealValue(10)];
    }
    return _moneyLab;
}

-(UILabel *)healthLab{
    if (!_healthLab) {
        _healthLab = [[UILabel alloc] initWithTitle:@"健康:100" color:HEXColor(0x000000, 1) sizeFont:GGRealValue(10)];
    }
    return _healthLab;
}

-(UILabel *)reputationLab{
    if (!_reputationLab) {
        _reputationLab = [[UILabel alloc] initWithTitle:@"名声:100" color:HEXColor(0x000000, 1) sizeFont:GGRealValue(10)];
    }
    return _reputationLab;
}

-(UILabel *)depositLab{
    if (!_depositLab) {
        _depositLab = [[UILabel alloc] initWithTitle:@"存款:￥0" color:HEXColor(0x000000, 1) sizeFont:GGRealValue(10)];
    }
    return _depositLab;
}

-(UILabel *)weekLab{
    if (!_weekLab) {
        _weekLab = [[UILabel alloc] initWithTitle:@"周:100" color:HEXColor(0x000000, 1) sizeFont:GGRealValue(10)];
    }
    return _weekLab;
}

-(UIButton *)reSiteBtn{
    if (!_reSiteBtn) {
        _reSiteBtn = [UIButton new];
        [_reSiteBtn setBackgroundColor:HEXColor(0xffffff, 1)];
        [_reSiteBtn setTitleColor:HEXColor(0x000000, 1) forState:UIControlStateNormal];
        [_reSiteBtn setTitle:@"更换区域" forState:UIControlStateNormal];
        _reSiteBtn.layer.borderColor = HEXColor(0x000000, 1).CGColor;
        _reSiteBtn.layer.borderWidth = 0.5;
        [_reSiteBtn addTarget:self action:@selector(reSiteBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _reSiteBtn;
}

-(UIButton *)aliPayBtn{
    if (!_aliPayBtn) {
        _aliPayBtn = [UIButton new];
        [_aliPayBtn setBackgroundColor:HEXColor(0x000000, 0)];
        [_aliPayBtn setTitleColor:HEXColor(0x000000, 1) forState:UIControlStateNormal];
        [_aliPayBtn setTitle:@"余额宝" forState:UIControlStateNormal];
        _aliPayBtn.layer.borderColor = HEXColor(0x000000, 1).CGColor;
        _aliPayBtn.layer.borderWidth = 0.5;
        [_aliPayBtn addTarget:self action:@selector(aliPayBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _aliPayBtn;
}

-(UIButton *)hospitalBtn{
    if (!_hospitalBtn) {
        _hospitalBtn = [UIButton new];
        [_hospitalBtn setBackgroundColor:HEXColor(0x000000, 0)];
        [_hospitalBtn setTitleColor:HEXColor(0x000000, 1) forState:UIControlStateNormal];
        [_hospitalBtn setTitle:@"医院" forState:UIControlStateNormal];
        _hospitalBtn.layer.borderColor = HEXColor(0x000000, 1).CGColor;
        _hospitalBtn.layer.borderWidth = 0.5;
        [_hospitalBtn addTarget:self action:@selector(hospitalBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _hospitalBtn;
}

-(UIButton *)intermediaryBtn{
    if (!_intermediaryBtn) {
        _intermediaryBtn = [UIButton new];
        [_intermediaryBtn setBackgroundColor:HEXColor(0x000000, 0)];
        [_intermediaryBtn setTitleColor:HEXColor(0x000000, 1) forState:UIControlStateNormal];
        [_intermediaryBtn setTitle:@"房产中介" forState:UIControlStateNormal];
        _intermediaryBtn.layer.borderColor = HEXColor(0x000000, 1).CGColor;
        _intermediaryBtn.layer.borderWidth = 0.5;
        [_intermediaryBtn addTarget:self action:@selector(intermediaryBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _intermediaryBtn;
}

-(UIButton *)settingBtn{
    if (!_settingBtn) {
        _settingBtn = [UIButton new];
//        [_settingBtn setImage:setIMG(@"LESettingIcon") forState:UIControlStateNormal];
        [_settingBtn setBackgroundImage:setIMG(@"DSESettingIcon") forState:UIControlStateNormal];
        [_settingBtn addTarget:self action:@selector(settingBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _settingBtn;
}

-(LEReSiteView *)reSiteView{
    if (!_reSiteView) {
        _reSiteView = [LEReSiteView LEReSiteViewWithArray:@[@"王府井",@"簋街",@"中关村",@"动物园",@"潘家园"] delegate:self];
//        _reSiteView.delegate = self;
    }
    WS(ws)
    _reSiteView.disBlock = ^(){
        ws.isOpenItem = nilOpen;
        ws.reSiteBtn.selected = NO;
    };
    return _reSiteView;
}
-(LESettingView *)settingView{
    if (!_settingView) {
        _settingView = [[LESettingView alloc] init];
        _settingView.delegate = self;
    }
    WS(ws)
    _settingView.disBlock = ^(){
        ws.isOpenItem = nilOpen;
        ws.settingBtn.selected = NO;
    };
        
    return _settingView;
}
-(LEAlipayView *)alipayView{
    if (!_alipayView) {
        _alipayView = [[LEAlipayView alloc] init];
        _alipayView.delegate = self;
    }
    WS(ws)
    _alipayView.disBlock = ^(){
        ws.isOpenItem = nilOpen;
        ws.aliPayBtn.selected = NO;
    };
    return _alipayView;
}
-(LEBuyVerifyView *)buyVerifyView{
    if (!_buyVerifyView) {
        _buyVerifyView = [[LEBuyVerifyView alloc] init];
        _buyVerifyView.delegate = self;
    }
    WS(ws)
    _buyVerifyView.disBlock = ^(){
        ws.isOpenItem = nilOpen;
    };
    return _buyVerifyView;
}
-(LEBuyVerifyView *)saleVerifyView{
    if (!_saleVerifyView) {
        _saleVerifyView = [[LEBuyVerifyView alloc] init];
        _saleVerifyView.delegate = self;
    }
    WS(ws)
    _saleVerifyView.disBlock = ^(){
        ws.isOpenItem = nilOpen;
    };
    return _saleVerifyView;
}
-(LEHintView *)hintView{
    if (!_hintView) {
        _hintView = [[LEHintView alloc] init];
    }
    WS(ws)
    _hintView.disBlock = ^(){
        ws.isOpenItem = nilOpen;
    };
    return _hintView;
}
-(LEHintView *)behaviorHintView{
    if (!_behaviorHintView) {
        _behaviorHintView = [[LEHintView alloc] init];
    }
    WS(ws)
    _behaviorHintView.disBlock = ^(){
        ws.isOpenItem = nilOpen;
    };
    return _behaviorHintView;
}
-(LEUserInfoModel *)userInfo{
    if (!_userInfo) {
        _userInfo = [LEUserInfoModel new];
        _userInfo.moneyNum = 100;
        _userInfo.reputationNum = 100;
        _userInfo.aliPayNum = 0;
        _userInfo.reputationNum = 100;
    }
    return _userInfo;
}
-(LEDefaultHintView *)reLoadHintView{
    if (!_reLoadHintView) {
        _reLoadHintView = [[LEDefaultHintView alloc] init];
        _reLoadHintView.delegate = self;
    }
    WS(ws)
    _reLoadHintView.disBlock = ^(){
        ws.isOpenItem = nilOpen;
    };
    return _reLoadHintView;
}
-(LEDefaultHintView *)gameOverView{
    if (!_gameOverView) {
        _gameOverView = [[LEDefaultHintView alloc] init];
        _gameOverView.delegate = self;
    }
    WS(ws)
    _gameOverView.disBlock = ^(){
        ws.isOpenItem = nilOpen;
    };
    return _gameOverView;
}
-(NSMutableArray *)nowDataSourceArrayM{
    if (!_nowDataSourceArrayM) {
        _nowDataSourceArrayM = [[NSMutableArray alloc] initWithCapacity:41];
    }

    return _nowDataSourceArrayM;
}
-(NSMutableArray *)myDataSourceArrayM{
    if (!_myDataSourceArrayM) {
        _myDataSourceArrayM = [[NSMutableArray alloc] initWithCapacity:41];
    }
    return _myDataSourceArrayM;
}
@end
